package com.mego.maq.activitys;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.mego.maq.R;
import com.mego.maq.utils.TripleDesHelper;


public class MainActivity2 extends Activity {

    EditText ipEdit;
    EditText portEdit;

    EditText sendET;
    EditText recvET;
    EditText mobileEdit;
    String _ip = "106.14.209.254";
    int _port = 8902;
    String _mobile = "13564508883";

    ConnectThread ct;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        ipEdit = (EditText) findViewById(R.id.ipEdit);
        portEdit = (EditText) findViewById(R.id.portEdit);

        mobileEdit = (EditText) findViewById(R.id.mobileEdit);
        _mobile = mobileEdit.getText().toString();

        recvET = (EditText) findViewById(R.id.recvET);
        sendET = (EditText) findViewById(R.id.sendET);

        Button sendbtn = (Button) findViewById(R.id.sendbtn);
        sendbtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                onSend();
            }
        });

        Button reset_btn = (Button) findViewById(R.id.reset_btn);
        reset_btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                onReset();
            }
        });

        onReset();


//        String line = "{\"action\":\"Buildings/Rooms/Devices/devHistories\",\"token\":\"F6FAEA99\",”page”:1,”rows”:20,”remark”:””}";
        String line = "enavi28960818";
        String kk = TripleDesHelper.defaultEncrypt(line);

        String HH = TripleDesHelper.defaultDecrypt(kk);
        _port = 8902;

    }

    boolean _isrunning = true;

    public void onReset() {
        _ip = ipEdit.getText().toString();
        _port = Integer.parseInt(portEdit.getText().toString());

        if (ct != null) {
            ct.interrupt();
            ct = null;
        }
        ct = new ConnectThread();
        ct.start();
    }

    public static final int FINISHSEND = 607;
    public static final int TCXC = 608;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case FINISHSEND:
                    String str = sendET.getText().toString();
                    Toast.makeText(MainActivity2.this, "[已经发送]" + str, Toast.LENGTH_SHORT).show();
                    break;
                case TCXC:
                    Toast.makeText(MainActivity2.this, "已退出", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public void onSend() {

        //网络请求必需用线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送数据
                try {
                    String msg = sendET.getText().toString();
                    ct.outputStream.write(msg.getBytes());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(FINISHSEND);
            }
        }).start();

    }

    class ConnectThread extends Thread {
        Socket socket = null;        //定义socket
        OutputStream outputStream = null;    //定义输出流（发送）
        InputStream inputStream = null;    //定义输入流（接收）
        MainActivity2 ma;

        public void run() {
            System.out.println(Thread.currentThread().getName() + ": Hello");
            try {
                socket = new Socket(_ip, _port);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //获取输出流
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                while (true) {
                    final byte[] buffer = new byte[1024];//创建接收缓冲区
                    inputStream = socket.getInputStream();
                    final int len = inputStream.read(buffer);//数据读出来，并且返回数据的长度
                    runOnUiThread(new Runnable()//不允许其他线程直接操作组件，用提供的此方法可以
                    {
                        public void run() {
                            recvET.append(new String(buffer, 0, len) + "\r\n");
                        }
                    });
                    if (!_isrunning) {
                        mHandler.sendEmptyMessage(TCXC);
                        return;
                    }
                }
            } catch (IOException e) {

            }

        }
    }

}
